<template>
    <div class="checkRequest" style="background-color: white;margin: 30px;padding: 30px;">
    <el-form
      ref="ruleFormRef"
      style="max-width: 1300px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
    <el-popconfirm title="你确定?" @confirm="resetForm">
    <template #reference>
      <el-button style=" width: 100px;margin-bottom: 30px;"  type="danger" @click="resetForm">重置检查患者</el-button>
    </template>
  </el-popconfirm>
  
      <el-form-item label="检查申请" prop="name">
        <el-tag type="success">检查项目金额合计为：{{checkPrice}}</el-tag>
        <el-table
    ref="multipleTableRef"
    :data="tableData"
    style="width: 100%"
    @selection-change="handleSelectionChange"
    size="mini"
  >
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column property="techName" label="项目" width="120" />
    <el-table-column  label="加急" property="isFire"/>
    <el-table-column label="检查科室ID" :label-width="formLabelWidth" property="deptId">
    </el-table-column>
    <el-table-column property="techPrice" label="单价" />
    <el-table-column property="pricetype" label="价格类型" />
    <el-table-column label="操作" width="300">
  <template #header >
    <el-button text @click="dialog = true" type="primary">增加</el-button>
    <el-popconfirm title="你确定?" @confirm="deleteSelectedItems">
    <template #reference>
      <el-button  type="danger"  plain stype="margin:10px" >删除</el-button> 
    </template>
  </el-popconfirm>
     <el-button type="success" @click="saveSelectedItems"  plain stype="margin:10px" >刷新</el-button>
  </template>
  </el-table-column> 
  <template v-if="!tableData.length">
    <div>暂无数据</div>
  </template>
  </el-table>
</el-form-item>     

<el-drawer
    v-model="dialog"
    title="新增检查申请"
    :before-close="handleClose"
    direction="ltr"
    class="demo-drawer"
   
  >
    <div class="demo-drawer__content">
      <el-form :model="form">
        <el-form-item>
          是否加急 &nbsp <el-switch    v-model="form.isFire"
          inline-prompt active-text="是" inactive-text="否" ></el-switch> 
        </el-form-item>
        <el-form-item label="检查科室" :label-width="formLabelWidth" property="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择科室"
            @click="selectCheckDept()" 
          >
            <el-option v-for="item in deptList" :label="item.deptName" :value="item.deptId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="检查名称" :label-width="formLabelWidth">
          <el-input v-model="form.techName" style="width: 300px;" autocomplete="off" placeholder="请输入检查名称"/>
        </el-form-item>
        <el-form-item label="检查编码" :label-width="formLabelWidth">
          <el-input v-model="form.techCode" style="width: 300px;" autocomplete="off" placeholder="或请输入检查编码"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectChecks()">搜索</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-table :data="tableData">
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="id" label="项目编号"></el-table-column>
            <el-table-column prop="techType" label="分类"></el-table-column>
            <el-table-column prop="techName" label="项目"></el-table-column>
          </el-table>
        </el-form-item>
      
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">
          {{ loading ? '正在提交中' : '确定' }}
        </el-button>
      </div>
    </div>
  </el-drawer>
  <el-form-item label="检查科室" :label-width="formLabelWidth" prop="name"> 
          <el-select
            v-model="form.deptId" style="width: 200px;"
            placeholder="请选择科室"
            @click="selectCheckDept()" disabled
          >
            <el-option v-for="item in deptList" :label="item.deptName" :value="item.deptId"   />
          </el-select>
  </el-form-item>
  <el-form-item label="检查医生" :label-width="formLabelWidth" prop="employeeId"> 
          <el-select
            v-model="form.employeeId" style="width: 200px;"
            placeholder="请选择医生"
            @click="selectDoctor()"  
          >
            <el-option v-for="item in doctors" :label="item.realName" :value="item.id"   />
          </el-select>
  </el-form-item>
<el-form-item label="检查目的" prop="checkInfo" >
<el-input style="width: 700px;height: 50px;" v-model="ruleForm.checkInfo" placeholder="请输入检查目的"></el-input>
</el-form-item>


<el-form-item label="检查位置" prop="checkPosition">
<el-input style="width: 700px;height: 50px;" v-model="ruleForm.checkPosition" placeholder="请输入检查位置"></el-input>
</el-form-item>

<el-form-item label="检查备注" prop="checkRemark">
<el-input style="width: 700px;height: 50px;" v-model="ruleForm.checkRemark" placeholder="请输入检查备注"></el-input>
</el-form-item>

<el-form-item  >
<el-input v-show="false" v-model="ruleForm.createTime" style="width: 700px;height: 50px;" placeholder="检查时间"></el-input>
</el-form-item>
<el-form-item>
        <el-button style="margin-left: 200px;width: 100px;"  type="primary" @click="submitCheckRequest()">提交</el-button>
        <el-button style=" width: 100px;margin-left: 100px;"  type="danger" @click="resetCheckRequest()">重置</el-button>
        <el-button style=" width: 100px;margin-left: 100px;"  type="success" @click="saveCheckRequest()">暂存检查申请</el-button>
        <el-button  style="margin-left: 100px;width: 100px;" type="warning"   @click="goToBookIndex">首页</el-button>
</el-form-item>

   
















  
    </el-form>
  </div>
 <!--检验申请页面-->
 <div class="inspectionRequest" style="background-color: white;margin: 30px;padding: 30px;">
    <el-form
      ref="ruleFormInspectionRef"
      style="max-width: 1300px"
      :model="ruleFormInspection"
      :rules="rulesInspection"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
    <el-popconfirm title="你确定?" @confirm="resetInspectionForm">
    <template #reference>
      <el-button style=" width: 100px;margin-bottom: 30px;"  type="danger" @click="resetInspectionForm">重置检验患者</el-button>
    </template>
  </el-popconfirm>
  
      <el-form-item label="检验申请" prop="name">
        <el-tag type="success">检验项目金额合计为：{{inspectionPrice}}</el-tag>
        <el-table
    ref="multipleTableRefInspection"
    :data="tableDataInspection"
    style="width: 100%"
    @selection-change="handleInspectionSelectionChange"
    size="mini"
  >
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column property="techName" label="项目" width="120" />
    <el-table-column  label="加急" property="isFire"/>
    <el-table-column label="检验科室ID" :label-width="formLabelWidth" property="deptId">
    </el-table-column>
    <el-table-column property="techPrice" label="单价" />
    <el-table-column property="pricetype" label="价格类型" />
    <el-table-column label="操作" width="300">
  <template #header >
    <el-button text @click="dialogInspection= true" type="primary">增加</el-button>
    <el-popconfirm title="你确定?" @confirm="deleteInspectionSelectedItems">
    <template #reference>
      <el-button  type="danger"  plain stype="margin:10px" >删除</el-button> 
    </template>
  </el-popconfirm>
     <el-button type="success" @click="saveInspectionSelectedItems"  plain stype="margin:10px" >刷新</el-button>
  </template>
  </el-table-column> 
  </el-table>
</el-form-item>     

<el-drawer
    v-model="dialogInspection"
    title="新增检验申请"
    :before-close="handleInspectionClose"
    direction="ltr"
    class="demo-drawer"
   
  >
    <div class="demo-drawer__content">
      <el-form :model="formInspection">
        <el-form-item>
          是否加急 &nbsp <el-switch    v-model="form.isFire"
          inline-prompt active-text="是" inactive-text="否" ></el-switch> 
        </el-form-item>
        <el-form-item label="检验科室" :label-width="formLabelWidth" property="deptId">
          <el-select
            v-model="formInspection.deptId"
            placeholder="请选择科室"
            @click="selectInspectionDept()" 
          >
            <el-option v-for="item in deptListInspection" :label="item.deptName" :value="item.deptId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="检验名称" :label-width="formLabelWidth">
          <el-input v-model="formInspection.techName" style="width: 300px;" autocomplete="off" placeholder="请输入检验名称"/>
        </el-form-item>
        <el-form-item label="检验编码" :label-width="formLabelWidth">
          <el-input v-model="formInspection.techCode" style="width: 300px;" autocomplete="off" placeholder="或请输入检验编码"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectInspections()">搜索</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-table :data="tableDataInspection">
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="id" label="项目编号"></el-table-column>
            <el-table-column prop="techType" label="分类"></el-table-column>
            <el-table-column prop="techName" label="项目"></el-table-column>
          </el-table>
        </el-form-item>
      
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">
          {{ loading ? '正在提交中' : '确定' }}
        </el-button>
      </div>
    </div>
  </el-drawer>
  <el-form-item label="检验科室" :label-width="formLabelWidth" prop="name"> 
          <el-select
            v-model="formInspection.deptId" style="width: 200px;"
            placeholder="请选择科室"
            @click="selectInspectionDept()" disabled
          >
            <el-option v-for="item in deptListInspection" :label="item.deptName" :value="item.deptId"   />
          </el-select>
  </el-form-item>
  <el-form-item label="检验医生" :label-width="formLabelWidth" prop="employeeId"> 
          <el-select
            v-model="formInspection.employeeId" style="width: 200px;"
            placeholder="请选择医生"
            @click="selectDoctorInspection()"  
          >
            <el-option v-for="item in doctorsInspection" :label="item.realName" :value="item.id"   />
          </el-select>
  </el-form-item>
<el-form-item label="检验目的" prop="inspectionInfo" >
<el-input style="width: 700px;height: 50px;" v-model="ruleFormInspection.inspectionInfo" placeholder="请输入检验目的"></el-input>
</el-form-item>


<el-form-item label="检验位置" prop="inspectionPosition">
<el-input style="width: 700px;height: 50px;" v-model="ruleFormInspection.inspectionPosition" placeholder="请输入检验位置"></el-input>
</el-form-item>

<el-form-item label="检验备注" prop="inspectionRemark">
<el-input style="width: 700px;height: 50px;" v-model="ruleFormInspection.inspectionRemark" placeholder="请输入检验备注"></el-input>
</el-form-item>

<el-form-item  >
<el-input v-show="false" v-model="ruleFormInspection.createTime" style="width: 700px;height: 50px;" placeholder="检验时间"></el-input>
</el-form-item>
<el-form-item>
        <el-button style="margin-left: 200px;width: 100px;"  type="primary" @click="submitInspectionRequest()">提交</el-button>
        <el-button style=" width: 100px;margin-left: 100px;"  type="danger" @click="resetInspectionRequest()">重置</el-button>
        <el-button style=" width: 100px;margin-left: 100px;"  type="success" @click="saveInspectionRequest()">暂存检验申请</el-button>
        <el-button  style="margin-left: 100px;width: 100px;" type="warning"   @click="goToBookIndex()">首页</el-button>
</el-form-item>
    </el-form>
  </div>
 <!--处置申请页面-->
 
 <div class="disposalRequest" style="background-color: white;margin: 30px;padding: 30px;">
 
  <el-form
      ref="ruleFormDisposalRef"
      style="max-width: 1300px"
      :model="ruleFormDisposal"
      :rules="rulesDisposal"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
    <el-popconfirm title="你确定?" @confirm="resetDisposalForm">
    <template #reference>
      <el-button style=" width: 100px;margin-bottom: 30px;"  type="danger" @click="resetDisposalForm">重置处置患者</el-button>
    </template>
  </el-popconfirm>
  
      <el-form-item label="处置申请" prop="name">
        <el-tag type="success">处置项目金额合计为：{{disposalPrice}}</el-tag>
        <el-table
    ref="multipleTableRefDisposal"
    :data="tableDataDisposal"
    style="width: 100%"
    @selection-change="handleDisposalSelectionChange"
    size="mini"
  >
    <el-table-column type="selection" :selectable="selectable" width="55" />
    <el-table-column property="techName" label="项目" width="120" />
    <el-table-column  label="加急" property="isFire"/>
    <el-table-column label="处置科室ID" :label-width="formLabelWidth" property="deptId">
    </el-table-column>
    <el-table-column property="techPrice" label="单价" />
    <el-table-column property="pricetype" label="价格类型" />
    <el-table-column label="操作" width="300">
  <template #header >
    <el-button text @click="dialogDisposal = true" type="primary">增加</el-button>
    <el-popconfirm title="你确定?" @confirm="deleteDisposalSelectedItems">
    <template #reference>
      <el-button  type="danger"  plain stype="margin:10px" >删除</el-button> 
    </template>
  </el-popconfirm>
     <el-button type="success" @click="saveDisposalSelectedItems"  plain stype="margin:10px" >刷新</el-button>
  </template>
  </el-table-column> 
  </el-table>
</el-form-item>     

<el-drawer
    v-model="dialogDisposal"
    title="新增处置申请"
    :before-close="handleDisposalClose"
    direction="ltr"
    class="demo-drawer"
   
  >
    <div class="demo-drawer__content">
      <el-form :model="formDisposal">
        <el-form-item>
          是否加急 &nbsp <el-switch    v-model="form.isFire"
          inline-prompt active-text="是" inactive-text="否" ></el-switch> 
        </el-form-item>
        <el-form-item label="处置科室" :label-width="formLabelWidth" property="deptId">
          <el-select
            v-model="formDisposal.deptId"
            placeholder="请选择科室"
            @click="selectDisposalDept()" 
          >
            <el-option v-for="item in deptListDisposal" :label="item.deptName" :value="item.deptId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="处置名称" :label-width="formLabelWidth">
          <el-input v-model="formDisposal.techName" style="width: 300px;" autocomplete="off" placeholder="请输入处置名称"/>
        </el-form-item>
        <el-form-item label="处置编码" :label-width="formLabelWidth">
          <el-input v-model="formDisposal.techCode" style="width: 300px;" autocomplete="off" placeholder="或请输入处置编码"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="selectDisposals()">搜索</el-button>
        </el-form-item>
        
        <el-form-item>
          <el-table :data="tableDataDisposal">
            <el-table-column type="selection"></el-table-column>
            <el-table-column prop="id" label="项目编号"></el-table-column>
            <el-table-column prop="techType" label="分类"></el-table-column>
            <el-table-column prop="techName" label="项目"></el-table-column>
          </el-table>
        </el-form-item>
      
      </el-form>
      <div class="demo-drawer__footer">
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" :loading="loading" @click="onClick">
          {{ loading ? '正在提交中' : '确定' }}
        </el-button>
      </div>
    </div>
  </el-drawer>
  <el-form-item label="处置科室" :label-width="formLabelWidth" prop="name"> 
          <el-select
            v-model="formDisposal.deptId" style="width: 200px;"
            placeholder="请选择科室"
            @click="selectCheckDept()" disabled
          >
            <el-option v-for="item in deptListDisposal" :label="item.deptName" :value="item.deptId"   />
          </el-select>
  </el-form-item>
  <el-form-item label="处置医生" :label-width="formLabelWidth" prop="employeeId"> 
          <el-select
            v-model="formDisposal.employeeId" style="width: 200px;"
            placeholder="请选择医生"
            @click="selectDoctorDisposal()"  
          >
            <el-option v-for="item in doctorsDisposal" :label="item.realName" :value="item.id"   />
          </el-select>
  </el-form-item>
<el-form-item label="处置目的" prop="disposalInfo" >
<el-input style="width: 700px;height: 50px;" v-model="ruleFormDisposal.disposalInfo" placeholder="请输入处置目的"></el-input>
</el-form-item>


<el-form-item label="处置位置" prop="disposalPosition">
<el-input style="width: 700px;height: 50px;" v-model="ruleFormDisposal.disposalPosition" placeholder="请输入处置位置"></el-input>
</el-form-item>

<el-form-item label="处置备注" prop="disposalRemark">
<el-input style="width: 700px;height: 50px;" v-model="ruleFormDisposal.disposalRemark" placeholder="请输入处置备注"></el-input>
</el-form-item>

<el-form-item  >
<el-input v-show="false" v-model="ruleFormDisposal.createTime" style="width: 700px;height: 50px;" placeholder="处置时间"></el-input>
</el-form-item>
<el-form-item>
        <el-button style="margin-left: 200px;width: 100px;"  type="primary" @click="submitDisposalRequest()">提交</el-button>
        <el-button style=" width: 100px;margin-left: 100px;"  type="danger" @click="resetDisposalRequest()">重置</el-button>
        <el-button style=" width: 100px;margin-left: 100px;"  type="success" @click="saveDisposalRequest()">暂存处置申请</el-button>
        <el-button  style="margin-left: 100px;width: 100px;" type="warning"   @click="goToBookIndex">首页</el-button>
</el-form-item>
    </el-form>











 </div>
















 
       <!--todo:提交全部申请按钮-->
        <el-button style="margin-left: 230px;width: 300px;" @click="allSubmit"  type="primary" >全部提交</el-button>
        <el-button  style="margin-left: 30px;width: 300px;"   @click="goToBookIndex">返回首页</el-button>
     
   

  </template>
  
  <script lang="ts" setup name="CheckRequest">
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import type { TableInstance } from 'element-plus'
import router from '@/router';
import { ElDrawer, ElMessageBox, ElNotification } from 'element-plus'
import axiosInstance from '@/utils/axiosUtils';
import { RefSymbol } from '@vue/reactivity';
const formLabelWidth = '80px'
interface User {
   id:number,
   techName: string,
   deptId:number,
   isFire: boolean,
   techPrice:number,
   pricetype: string,
   techType: string,
}
let timer=ref(null)
//各个项目金额
let checkPrice=ref(0);
let inspectionPrice=ref(0);
let disposalPrice=ref(0);
//各个项目对话框引用
const dialog = ref(false)
const dialogInspection = ref(false)
const dialogDisposal = ref(false)
const loading = ref(false)
//各个项目的科室信息
const deptList=ref([]);
const deptListInspection=ref([]);
const deptListDisposal=ref([]);
//各个项目的选中项引用
const multipleTableRef = ref<TableInstance>()
const multipleInspectionTableRef = ref<TableInstance>()
const multipleDisposalTableRef = ref<TableInstance>()
//各个项目的选中项
const multipleSelection = ref<User[]>([])
const multipleInspectionSelection = ref<User[]>([])
const multipleDisposalSelection = ref<User[]>([])
//各个项目的表单信息
const form = reactive({
  techName: '',
  techCode: '',
  deptId: '',
  isFire:  '',
  techPrice: '',
  pricetype: '',
  techType: '',
  employeeId:'',
})
const formInspection = reactive({
  techName: '',
  techCode: '',
  deptId: 0,
  isFire: null,
  techPrice: '',
  pricetype: '',
  techType: '',
  employeeId:null,
})
const formDisposal = reactive({
  techName: '',
  techCode: '',
  deptId: 0,
  isFire: null,
  techPrice: '',
  pricetype: '',
  techType: '',
  employeeId:null,
})
//各个项目的医生列表
const doctors=ref([
  {
   id:0,
   realName: '',
  }
]);
const doctorsInspection=ref([
  {
   id:0,
   realName: '',
  }
]);
const doctorsDisposal=ref([
  {
   id:0,
   realName: '',
  }
]);
//各个项目的表格数据
const tableData=ref( [
  {
     id:0,
     techName: '',
     isFire: null,
     deptId:null, 
     techPrice: null,
     pricetype:'',
     techType: '',
  }
])
const tableDataInspection=ref( [
  {
     id:0,
     techName: '',
     isFire: null,
     deptId:null, 
     techPrice: null,
     pricetype:'',
     techType: '',
  }
])
const tableDataDisposal=ref( [
  {
     id:0,
     techName: '',
     isFire: null,
     deptId:null, 
     techPrice: null,
     pricetype:'',
     techType: '',
  }
])
//各个项目的表单规则
  interface RuleForm {
  name: string,
  checkInfo: string,
  checkPosition: string,
  checkRemark: string,
  createTime: string,
  employeeId:number,
  }
 interface RuleFormInspection {
  name: string,
  inspectionInfo: string,
  inspectionPosition: string,
  inspectionRemark: string,
  createTime: string,
  employeeId:number,
  }
  interface RuleFormDisposal {
  name: string,
  disposalInfo: string,
  disposalPosition: string,
  disposalRemark: string,
  createTime: string,
  employeeId:number,
  }
  const formSize = ref<ComponentSize>('default')
  //各个项目的表单引用
  const ruleFormRef = ref<FormInstance>()
  const ruleFormInspectionRef = ref<FormInstance>()
  const ruleFormDisposalRef = ref<FormInstance>()
  //各个项目的表单规则
  const ruleForm = reactive<RuleForm>({
    name: '10000',
    checkInfo: '',
    checkPosition: '',
    checkRemark: '',
    createTime: '',   
    employeeId:null,
  })
  const ruleFormInspection = reactive<RuleFormInspection>({
    name: '10000',
    inspectionInfo: '',
    inspectionPosition: '',
    inspectionRemark: '', 
    createTime: '',
    employeeId:null,
  })
  const ruleFormDisposal = reactive<RuleFormDisposal>({
    name: '10000',
    disposalInfo: '',
    disposalPosition: '',
    disposalRemark: '',
    createTime: '',
    employeeId:null,
  })
const rules = reactive<FormRules<RuleForm>>({
    name: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    checkInfo: [
      { required: true, message: '请输入检查目的', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    checkPosition: [
      { required: true, message: '请输入检查位置', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    checkRemark: [
      { required: true, message: '请输入检查备注', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    employeeId: [
      { required: true, message: '请选择医生', trigger: ' blur' },
    ]
  })
const rulesInspection = reactive<FormRules<RuleFormInspection>>({
    name: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    inspectionInfo: [
      { required: true, message: '请输入检查目的', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    inspectionPosition: [
      { required: true, message: '请输入检查位置', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    inspectionRemark: [
      { required: true, message: '请输入检查备注', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    employeeId: [
      { required: true, message: '请选择医生', trigger: ' blur' },
    ]
  })
const rulesDisposal = reactive<FormRules<RuleFormDisposal>>({
    name: [
      { required: true, message: 'Please input Activity name', trigger: 'blur' },
      { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    disposalInfo: [
      { required: true, message: '请输入处置目的', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    disposalPosition: [
      { required: true, message: '请输入处置位置', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    disposalRemark: [
      { required: true, message: '请输入处置备注', trigger: 'blur' },
      { min: 3, max: 500, message: '长度在 3 到 500 个字符', trigger: 'blur' },
    ],
    employeeId: [
      { required: true, message: '请选择医生', trigger: ' blur' },
    ]
  })
//各个项目的表单校验函数
const saveCheckRequest=()=>{
  sessionStorage.setItem('PatientCheck',JSON.stringify(ruleForm));
}
const resetCheckRequest=()=>{
  sessionStorage.removeItem('PatientCheck');
}
const saveInspectionRequest=()=>{
  sessionStorage.setItem('PatientInspection',JSON.stringify(ruleFormInspection));
}
const resetInspectionRequest=()=>{
  sessionStorage.removeItem('PatientInspection');
}
const saveDisposalRequest=()=>{
  sessionStorage.setItem('PatientDisposal',JSON.stringify(ruleFormDisposal));
}
const resetDisposalRequest=()=>{  
  sessionStorage.removeItem('PatientDisposal');
}
//查询检查项目
  const selectChecks = () => {
  const params = {
    techName: null,
    techCode: null
  };

  if (form.techName === '' && form.techCode === '') {
    ElMessageBox.alert('请输入检查项目名称或编码');
    return;
  } else if (form.techName == null) {
    params.techCode = form.techCode;
  } else {
    params.techName = form.techName;
  }
  
  // 正确传递 params 作为查询参数
  axiosInstance.get('/api/medicalTechnology/selectChecksInfo', { params })
    .then(res => {
      console.log(res.data);
      
      // 不清空之前的数据，而是直接添加新数据
      res.data.forEach(item => {
        // 检查是否已经存在该项
        const exists = tableData.value.find(data => data.id === item.id);
        if (!exists) {
          tableData.value.push({
            id: item.id,
            techName: item.tech_name,
            deptId: form.deptId,
            isFire: form.isFire,
            techPrice: item.tech_price,
            pricetype: item.price_type,
            techType: item.tech_type
          });
        }
      });
      console.log('科室id', form.deptId);
      console.log('加急不', form.isFire);
    })
    .catch(err => {
      console.log(err);
      ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
    });
}
//查询检验项目
const selectInspections = () => {
  const params = {
    techName: null,
    techCode: null
  };

  if (formInspection.techName === '' && formInspection.techCode === '') {
    ElMessageBox.alert('请输入检验项目名称或编码');
    return;
  } else if (formInspection.techName == null) {
    params.techCode = formInspection.techCode;
  } else {
    params.techName = formInspection.techName;
  }
  
  // 正确传递 params 作为查询参数
  axiosInstance.get('/api/medicalTechnology/selectInspectionsInfo', { params })
    .then(res => {
      console.log(res.data);
      
      // 不清空之前的数据，而是直接添加新数据
      res.data.forEach(item => {
        // 检查是否已经存在该项
        const exists = tableDataInspection.value.find(data => data.id === item.id);
        if (!exists) {
          tableDataInspection.value.push({
            id: item.id,
            techName: item.tech_name,
            deptId: formInspection.deptId,
            isFire: formInspection.isFire,
            techPrice: item.tech_price,
            pricetype: item.price_type,
            techType: item.tech_type
          });
        }
      });
      console.log('科室id', formInspection.deptId);
      console.log('加急不', formInspection.isFire);
    })
    .catch(err => {
      console.log(err);
      ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
    });
}
//查询处置项目
const selectDisposals = () => {
  const params = {
    techName: null,
    techCode: null
  };

  if (formDisposal.techName === '' && formDisposal.techCode === '') {
    ElMessageBox.alert('请输入处置项目名称或编码');
    return;
  } else if (formDisposal.techName == null) {
    params.techCode = formDisposal.techCode;
  } else {
    params.techName = formDisposal.techName;
  }
  
  // 正确传递 params 作为查询参数
  axiosInstance.get('/api/medicalTechnology/selectDisposalsInfo', { params })
    .then(res => {
      console.log(res.data);
      
      // 不清空之前的数据，而是直接添加新数据
      res.data.forEach(item => {
        // 检查是否已经存在该项
        const exists = tableDataDisposal.value.find(data => data.id === item.id);
        if (!exists) {
          tableDataDisposal.value.push({
            id: item.id,
            techName: item.tech_name,
            deptId: formDisposal.deptId,
            isFire: formDisposal.isFire,
            techPrice: item.tech_price,
            pricetype: item.price_type,
            techType: item.tech_type
          });
        }
      });
      console.log('科室id', formDisposal.deptId);
      console.log('加急不', formDisposal.isFire);
    })
    .catch(err => {
      console.log(err);
      ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
    });
}
//获取检查科室列表
const selectCheckDept = () => {
  axiosInstance.get('/api/department/selectCheckDeptNameAndId').then(res => {
    console.log(res.data)
   
// 清空之前的 deptList，以防重复推入
deptList.value = [];  // 保证这里是清空 deptList.value，而不是 deptList
   res.data.forEach((item: { dept_name: any; id: any; dept_ode: any; dept_type: any; }) => {
    deptList.value.push({
      deptName: item.dept_name,
      deptId: item.id,
      deptOde: item.dept_ode,
      deptType: item.dept_type,
    })
    })
  }).catch(err => {
    console.log(err)
  })
 }
 //获取检验科室列表
const selectInspectionDept = () => {
  axiosInstance.get('/api/department/selectInspectionDeptNameAndId').then(res => {
    console.log(res.data)
   
// 清空之前的 deptList，以防重复推入  
deptListInspection.value = [];  // 保证这里是清空 deptList.value，而不是 deptList
   res.data.forEach((item: { dept_name: any; id: any; dept_ode: any; dept_type: any; }) => {
    deptListInspection.value.push({
      deptName: item.dept_name,
      deptId: item.id,
      deptOde: item.dept_ode,
      deptType: item.dept_type,
    })
    })
  }).catch(err => {
    console.log(err)
  })
 }
 //获取处置科室列表
const selectDisposalDept = () => {
  axiosInstance.get('/api/department/selectDisposalDeptNameAndId').then(res => {
    console.log(res.data)
   // 清空之前的 deptList，以防重复推入  
deptListDisposal.value = [];  // 保证这里是清空 deptList.value，而不是 deptList
   res.data.forEach((item: { dept_name: any; id: any; dept_ode: any; dept_type: any; }) => {
    deptListDisposal.value.push({
      deptName: item.dept_name,
      deptId: item.id,
      deptOde: item.dept_ode,
      deptType: item.dept_type,
    })
    })
  }).catch(err => {
    console.log(err)
  })
}
//根据科室id获取医生列表
const selectDoctor = () => {
  axiosInstance.get('/api/employee/selectDoctorsById', { params: { deptId: form.deptId } })
    .then(res => {
      console.log('返回的数据:', res.data);
      if (Array.isArray(res.data)) { // 确认返回的数据是数组
        doctors.value = []; // 清空医生列表（可选）
        res.data.forEach(item => {
          doctors.value.push({
            id: item.id,              // 假设 Employee 类中有这些属性
            realName: item.realname,  // 需要确认 Employee 类中有 realName 属性
          });
        });
        console.log('医生列表', doctors.value);
      } else {
        console.error('数据格式错误，期望数组，但实际为:', typeof res.data);
        ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
      }
    })
    .catch(err => {
      console.log(err);
      ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
    });
}
//根据检验科室id获取医生列表
const selectDoctorInspection = () => {
  axiosInstance.get('/api/employee/selectDoctorsById',
   { params: { deptId: formInspection.deptId } })
    .then(res => {
      console.log('返回的数据:', res.data);
      if (Array.isArray(res.data)) { // 确认返回的数据是数组
        doctorsInspection.value = []; // 清空医生列表（可选）
        res.data.forEach(item => {
          doctorsInspection.value.push({
            id: item.id,              // 假设 Employee 类中有这些属性
            realName: item.realname,  // 需要确认 Employee 类中有 realName 属性
          });
        });
        console.log('医生列表', doctorsInspection.value);
      } else {
        console.error('数据格式错误，期望数组，但实际为:', typeof res.data);
        ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
      }
    })
    .catch(err => {
      console.log(err);
      ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
    });
}
//根据处置科室id获取医生列表
const selectDoctorDisposal = () => {
  axiosInstance.get('/api/employee/selectDoctorsById', { params: { deptId: formDisposal.deptId } })
    .then(res => {
      console.log('返回的数据:', res.data);
      if (Array.isArray(res.data)) { // 确认返回的数据是数组
        doctorsDisposal.value = []; // 清空医生列表（可选）
        res.data.forEach(item => {
          doctorsDisposal.value.push({
            id: item.id,              // 假设 Employee 类中有这些属性
            realName: item.realname,  // 需要确认 Employee 类中有 realName 属性
          });
        });
        console.log('医生列表', doctorsDisposal.value);
      } else {
        console.error('数据格式错误，期望数组，但实际为:', typeof res.data);
        ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
      }
    })
    .catch(err => {
      console.log(err);
      ElMessageBox.alert('获取数据失败，请重试'); // 提示用户请求失败
    });
}
const onClick = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false
    dialog.value = false
  }, 400);
}
const cancelForm = () => {
  loading.value = false
  dialog.value = false
  clearTimeout(timer)
}
const handleClose = (done) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('Do you want to submit?')
    .then(() => {
      loading.value = true
      timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 400)
    })
    .catch(() => {
      // catch error
    })
}
const handleInspectionClose = (done) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('Do you want to submit?')
    .then(() => {
      loading.value = true
      timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 400)
    })
    .catch(() => {
      // catch error
    })
}
const handleDisposalClose = (done) => {
  if (loading.value) {
    return
  }
  ElMessageBox.confirm('Do you want to submit?')
    .then(() => {
      loading.value = true
      timer = setTimeout(() => {
        done()
        // 动画关闭需要一定的时间
        setTimeout(() => {
          loading.value = false
        }, 400)
      }, 400)
    })
    .catch(() => {
      // catch error
    })
}
//处理选中项
const handleSelectionChange = (val: User[]) => {
  calculateCheckPrice(val);
  multipleSelection.value = val;
  console.log("被选中项：",multipleSelection.value);
};
//处理检验选中项
const handleInspectionSelectionChange = (val: User[]) => {
  calculateInspectionPrice(val);
  multipleInspectionSelection.value = val;
  console.log("被检验选中项：",multipleInspectionSelection.value);
};
//处理处置选中项
const handleDisposalSelectionChange = (val: User[]) => {
  calculateDisposalPrice(val);
  multipleDisposalSelection.value = val;
  console.log("被处置选中项：",multipleDisposalSelection.value);
};
 
//计算总金额
const calculateCheckPrice = (selectedItems) => {
  checkPrice.value = selectedItems.reduce((total, item) => {
    return total + (Number(item.techPrice) || 0); // 累加单价
  }, 0);
};
//计算检验总金额
const calculateInspectionPrice = (selectedItems) => {
  inspectionPrice.value = selectedItems.reduce((total, item) => {
    return total + (Number(item.techPrice) || 0); // 累加单价
  }, 0);
};
//计算处置总金额
const calculateDisposalPrice = (selectedItems) => {
  disposalPrice.value = selectedItems.reduce((total, item) => {
    return total + (Number(item.techPrice) || 0); // 累加单价
  }, 0);
};
//刷新选中项
const saveSelectedItems = () => {
  //使其重新加载数据
  handleSelectionChange(multipleSelection.value);
  // 在这里实现保存逻辑，根据业务需求处理选中的项目
  console.log('已选中项：', multipleSelection.value); // 打印选中的项目
  // 可以将选中的项目保存到某个状态或发起 API 请求
  ElNotification({
    title: '成功',
    message: '已选中' + multipleSelection.value.length + '项',
    type:'success',
    duration: 400
  }); // 显示成功提示
};
//刷新检验选中项
const saveInspectionSelectedItems = () => {
  //使其重新加载数据
  handleInspectionSelectionChange(multipleInspectionSelection.value);
  // 在这里实现保存逻辑，根据业务需求处理选中的项目
  console.log('已检验选中项：', multipleInspectionSelection.value); // 打印选中的项目
  // 可以将选中的项目保存到某个状态或发起 API 请求
  ElNotification({
    title: '成功',
    message: '已检验选中' + multipleInspectionSelection.value.length + '项',
    type:'success',
    duration: 400
  }); // 显示成功提示
};
//刷新处置选中项
const saveDisposalSelectedItems = () => {
  //使其重新加载数据
  handleDisposalSelectionChange(multipleDisposalSelection.value);
  // 在这里实现保存逻辑，根据业务需求处理选中的项目
  console.log('已处置选中项：', multipleDisposalSelection.value); // 打印选中的项目
  // 可以将选中的项目保存到某个状态或发起 API 请求
  ElNotification({
    title: '成功',
    message: '已处置选中' + multipleDisposalSelection.value.length + '项',
    type:'success',
    duration: 400
  }); // 显示成功提示
};
//删除选中项========》遍历每个项的id，被选中的项的id不等于tabledata中的id，则删除
const deleteSelectedItems = () => {
   if(multipleSelection.value.length === 0){
    ElNotification({
      title: '警告',
      message: '请先选择要删除的项',
      type: 'warning',
      duration: 400
    })
   
   }else{
  console.log('已选中项：', multipleSelection.value); // 打印选中的项目
   // 从 tableData 中移除选中的项
   multipleSelection.value.forEach(selectedItem => {
      tableData.value = tableData.value.filter(item => item.id !== selectedItem.id);
  });
     // 清空选中项
    multipleSelection.value = [];
    multipleTableRef.value?.clearSelection();
  ElNotification({
    title: '成功',
    message: '已删除',
    type:'success',
    duration: 400
  }); // 显示成功提示
}
}
//删除检验选中项========》遍历每个项的id，被选中的项的id不等于tabledata中的id，则删除
const deleteInspectionSelectedItems = () => {
   if(multipleInspectionSelection.value.length === 0){
    ElNotification({
      title: '警告',
      message: '请先选择要删除的项',
      type: 'warning',
      duration: 400
    })
   
   }else{
  console.log('已检验选中项：', multipleInspectionSelection.value); // 打印选中的项目
   // 从 tableData 中移除选中的项
   multipleInspectionSelection.value.forEach(selectedItem => {
      tableDataInspection.value = tableDataInspection.value.filter(item => item.id !== selectedItem.id);
  });
     // 清空选中项
    multipleInspectionSelection.value = [];
    multipleInspectionTableRef.value?.clearSelection();
  ElNotification({
    title: '成功',
    message: '已删除',
    type:'success',
    duration: 400
  }); // 显示成功提示
}
}
//删除处置选中项========》遍历每个项的id，被选中的项的id不等于tabledata中的id，则删除
const deleteDisposalSelectedItems = () => {
   if(multipleDisposalSelection.value.length === 0){
    ElNotification({
      title: '警告',
      message: '请先选择要删除的项',
      type: 'warning',
      duration: 400
    })
   
   }else{
  console.log('已处置选中项：', multipleDisposalSelection.value); // 打印选中的项目
   // 从 tableData 中移除选中的项
   multipleDisposalSelection.value.forEach(selectedItem => {
      tableDataDisposal.value = tableDataDisposal.value.filter(item => item.id !== selectedItem.id);
  });
     // 清空选中项
    multipleDisposalSelection.value = [];
    multipleDisposalTableRef.value?.clearSelection();
  ElNotification({
    title: '成功',
    message: '已删除',
    type:'success',
    duration: 400
  }); // 显示成功提示
}
}
//返回首页
const goToBookIndex = () => {
  router.push({ name: 'bookIndex' })
}
const selectable = (row: User) => ![1, 2].includes(row.id)
 
 const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需加1，并补零
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
 const medicalTechnologyIds=tableData.value.map(item=>item.id)
 //构建提交检查申请表单数据
 const createSubmitChecksData = () => {
  if(multipleSelection.value.length === 0){
    ElNotification({
      title: '警告',
      message: '请先选择检查项目',
      type: 'warning',
      duration: 400
    })
  }else{
    const submitChecksData = multipleSelection.value.map(selectedItem => ({
        id: null, // 选中项的 id
        medicalTechnologyId: selectedItem.id, // 选中项的 id
        techName: selectedItem.techName, // 选中项的 techName
        registerId: JSON.parse(sessionStorage.getItem('Patient') || '{}').id, // 从 sessionStorage 获取 registerId
        checkInfo: ruleForm.checkInfo, // 从表单获取检查信息
        checkPosition: ruleForm.checkPosition, // 从表单获取检查位置
        checkRemark: ruleForm.checkRemark, // 从表单获取检查备注
        creationTime: formatDate(new Date()), // 获取当前时间
        checkEmployeeId: form.employeeId, // 从表单获取部门 ID
        inputcheckEmployeeId: null, // 此项保持为 null
        checkTime: null, // 此项保持为 null
        checkResult: null, // 此项保持为 null
        checkState: '已开立' // 默认状态
    }));
    return submitChecksData; // 返回生成的数组对象
}
  }
 //构建提交检验申请表单数据
 const createSubmitInspectionsData = () => {
  if(multipleInspectionSelection.value.length === 0){
    ElNotification({
      title: '警告',
      message: '请先选择检验项目',
      type: 'warning',
      duration: 400
    })
  }else{
    const submitInspectionsData = multipleInspectionSelection.value.map(selectedItem => ({
        id: null, // 选中项的 id
        medicalTechnologyId: selectedItem.id, // 选中项的 id
        techName: selectedItem.techName, // 选中项的 techName
        registerId: JSON.parse(sessionStorage.getItem('Patient') || '{}').id, // 从 sessionStorage 获取 registerId
        inspectionInfo: ruleFormInspection.inspectionInfo, // 从表单获取检验信息
        inspectionPosition: ruleFormInspection.inspectionPosition, // 从表单获取检验位置
        inspectionRemark: ruleFormInspection.inspectionRemark, // 从表单获取检验备注
        creationTime: formatDate(new Date()), // 获取当前时间
        inspectionEmployeeId: formInspection.employeeId, // 从表单获取部门 ID
        inputinspectionEmployeeId: null, // 此项保持为 null
        inspectionTime: null, // 此项保持为 null
        inspectionResult: null, // 此项保持为 null
        inspectionState: '已开立' // 默认状态
    }));    
    return submitInspectionsData; // 返回生成的数组对象
}
  }
 //构建提交处置申请表单数据
 const createSubmitDisposalsData = () => {
  if(multipleDisposalSelection.value.length === 0){
    ElNotification({
      title: '警告',
      message: '请先选择处置项目',
      type: 'warning',
      duration: 400
    })
  }else{
    const submitDisposalsData = multipleDisposalSelection.value.map(selectedItem => ({
        id: null, // 选中项的 id
        medicalTechnologyId: selectedItem.id, // 选中项的 id
        techName: selectedItem.techName, // 选中项的 techName
        registerId: JSON.parse(sessionStorage.getItem('Patient') || '{}').id, // 从 sessionStorage 获取 registerId
        disposalInfo: ruleFormDisposal.disposalInfo, // 从表单获取处置信息
        disposalPosition: ruleFormDisposal.disposalPosition, // 从表单获取处置位置
        disposalRemark: ruleFormDisposal.disposalRemark, // 从表单获取处置备注
        creationTime: formatDate(new Date()), // 获取当前时间
        disposalEmployeeId: formDisposal.employeeId, // 从表单获取部门 ID
        inputdisposalEmployeeId: null, // 此项保持为 null
        disposalTime: null, // 此项保持为 null
        disposalResult: null, // 此项保持为 null
        disposalState: '已开立' // 默认状态
    }));
    return submitDisposalsData; // 返回生成的数组对象
}
  }
 //提交检查申请表单
 const submitCheckRequest = () => {
   // 准备提交的数据，去掉重复的参数
  const submitChecksData = createSubmitChecksData();
  console.log('提交检查申请的数据：', submitChecksData);
  // 发送请求
  axiosInstance.post('/api/checkRequest/insertCheckRequest',submitChecksData,{
    headers: {
      'Content-Type': 'application/json' // 设置请求头为 JSON 格式
    }
  })
    .then(response => {
      console.log(response.data);
      ElNotification({
        title: '成功',
        message: '提交检查申请成功',
        type:'success',
        duration: 400
      })
    })
    .catch(err => {
      console.error(err);
      ElNotification.error({  
        title: '错误',
        message: '提交检查申请失败',
        duration: 400
      })
    })
    .finally(() => {
      loading.value = false; // 无论成功与否，最后都要重置加载状态
 
    });
 }
 //提交检验申请表单
 const submitInspectionRequest = () => {
   // 准备提交的数据，去掉重复的参数
  const submitInspectionsData = createSubmitInspectionsData();
  console.log('提交检验申请的数据：', submitInspectionsData);
  // 发送请求
  axiosInstance.post('/api/inspectionRequest/insertInspectionRequest',submitInspectionsData,{
    headers: {
      'Content-Type': 'application/json' // 设置请求头为 JSON 格式
    }
  })
    .then(response => {
      console.log(response.data);
      ElNotification({
        title: '成功',
        message: '提交检验申请成功',
        type:'success',
        duration: 400
      })
    })
    .catch(err => {
      console.error(err);
      ElNotification.error({  
        title: '错误',
        message: '提交检验申请失败',
        duration: 400
      })
    })
    .finally(() => {
      loading.value = false; // 无论成功与否，最后都要重置加载状态
 
    });
 }
 //提交处置申请表单
 const submitDisposalRequest = () => {
   // 准备提交的数据，去掉重复的参数
  const submitDisposalsData = createSubmitDisposalsData();
  console.log('提交处置申请的数据：', submitDisposalsData);
  // 发送请求
  axiosInstance.post('/api/disposalRequest/insertDisposalRequest',submitDisposalsData,{
    headers: {
      'Content-Type': 'application/json' // 设置请求头为 JSON 格式
    }
  })
    .then(response => {
      console.log(response.data);
      ElNotification({
        title: '成功',
        message: '提交处置申请成功',
        type:'success',
        duration: 400
      })
    })
    .catch(err => {
      console.error(err);
      ElNotification.error({  
        title: '错误',
        message: '提交处置申请失败',
        duration: 400
      })
    })
    .finally(() => {
      loading.value = false; // 无论成功与否，最后都要重置加载状态
 
    });
 }
 //重置检查申请表单
  const resetForm = () => {
    sessionStorage.removeItem('PatientCheck'); // 清空 sessionStorage 中的 Patient 数据
  }
  //重置检验申请表单
  const resetInspectionForm = () => {
    sessionStorage.removeItem('PatientInspection'); // 清空 sessionStorage 中的 Patient 数据    
  }
  //重置处置申请表单
  const resetDisposalForm = () => {
    sessionStorage.removeItem('PatientDisposal'); // 清空 sessionStorage 中的 Patient 数据    
}

 //全部提交处置申请表单
 const allSubmit=()=>{
  sessionStorage.removeItem('Patient'); // 清空 sessionStorage 中的 Patient 数据
 }
  </script>
